package cn.leo.dynamic_multi_datasource.aspect;

import cn.leo.dynamic_multi_datasource.annotation.TargetDatasource;
import cn.leo.dynamic_multi_datasource.datasource.DynamicDatasourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * 通过AOP，配置不同的数据源
 * @author leo.z.l
 * @create 2019-09-07  14:37
 */
@Aspect
@Order(-1)
@Component
public class DynamicDatasourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDatasourceAspect.class);

    @Before("@annotation(targetDatasource)")
    public void changeDataSource(JoinPoint point, TargetDatasource targetDatasource) throws Throwable {

        String dsId = targetDatasource.name();

        if (!DynamicDatasourceContextHolder.containDataSourceType(dsId)) {
            logger.error("数据源[{}]不存在，使用默认数据源 > {}", targetDatasource.name(), point.getSignature());
        } else {
            logger.debug("Use DataSource : {} > {}", targetDatasource.name(), point.getSignature());
            DynamicDatasourceContextHolder.setDataSourceType(dsId);
        }
    }

    @After("@annotation(targetDatasource)")
    public void restoreDataSource(JoinPoint point, TargetDatasource targetDatasource) {
        logger.debug("Revert DataSource : {} > {}", targetDatasource.name(), point.getSignature());
        DynamicDatasourceContextHolder.clearDataSourceType();
    }
}
